package cn.loioi.config;

import java.util.EnumSet;

import javax.servlet.DispatcherType;
import javax.servlet.FilterRegistration;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;

import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.filter.DelegatingFilterProxy;
import org.springframework.web.servlet.DispatcherServlet;

import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;

/**
 * Spring MVC 启动器（代替web.xml）
 * @文件 :SpringSartupInitializer.java
 * @作者 :cn.loioi
 * @创建时间 :2016年10月13日 下午1:12:26
 */
public class SpringSartupInitializer implements WebApplicationInitializer {
	@Override
	public void onStartup(ServletContext servletContext) throws ServletException {
		// 配置编码拦截器
		FilterRegistration.Dynamic characterEncoding = servletContext.addFilter("characterEncoding", new CharacterEncodingFilter("utf-8", true));
		characterEncoding.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), true, "*.json", "*.jspx");
		// Druid URL监控
		FilterRegistration.Dynamic druidFilter = servletContext.addFilter("druidFilter", new WebStatFilter());
		druidFilter.setInitParameter("exclusions", "/favicon.ico,/upload/*,/assets/*,/druid/*");
		druidFilter.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), true, "/*");
		// Shiro 安全框架拦截配置
		FilterRegistration.Dynamic shiroFilter = servletContext.addFilter("shiroFilter", new DelegatingFilterProxy());
		shiroFilter.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), true, "/admin/*");

		// 配置druid的SQL监控servlet
		ServletRegistration.Dynamic druidStatViewServlet = servletContext.addServlet("druidStatView", new StatViewServlet());
		druidStatViewServlet.setLoadOnStartup(1);
		druidStatViewServlet.setInitParameter("resetEnable", "true");
		druidStatViewServlet.setInitParameter("loginUsername", "druid");
		druidStatViewServlet.setInitParameter("loginPassword", "druid");
		druidStatViewServlet.addMapping("/druid/*");

		// 配置spring的DispatcherServlet
		DispatcherServlet dispatcher = new DispatcherServlet();
		dispatcher.setThrowExceptionIfNoHandlerFound(true);
		dispatcher.setContextClass(AnnotationConfigWebApplicationContext.class);
		dispatcher.setContextConfigLocation("cn.loioi.config.SpringMvcConfig");

		ServletRegistration.Dynamic dispatcherServlet = servletContext.addServlet("dispatcher", dispatcher);
		dispatcherServlet.setLoadOnStartup(1);
		dispatcherServlet.addMapping("/*");
	}
}